package com.ironman.analyze.core.handler;

import com.ironman.analyze.core.compute.entity.SpeedWindowData;
import com.ironman.common.params.SpeedParam;
import com.ironman.common.util.UnitConvertUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.function.Consumer;

@Slf4j
public class SpeedPostHandler extends BasePostHandler<SpeedWindowData> {

    private Double preSpeed = null;

    private final SpeedParam speedParam;

    public SpeedPostHandler(SpeedParam speedParam) {
        this.speedParam = speedParam;
    }

    @Override
    public void handler(SpeedWindowData data, Consumer<SpeedWindowData> consumer) {
        doHandler(data, consumer);
    }

    @Override
    public void threshold(SpeedWindowData data) {
        Double speed = data.getSpeed();
        if (Objects.isNull(speed)) {
            return;
        }

        if (preSpeed == null) {
            getCounter().incrementAndGet();
            preSpeed = speed;
            return;
        }

        double diff = Math.abs(speed - preSpeed);
        double unitConvert = UnitConvertUtil.unitConvert(speedParam.getSpeedThreshold(), speedParam.getSpeedUnit());
        if (diff > unitConvert) {
            getCounter().set(0);
            log.debug("船速触发对比阈值:{} 当前:{} 前一个:{} 相差:{} ", unitConvert, speed, preSpeed, diff);
            preSpeed = speed;
            return;
        }

        Integer countThreshold = speedParam.getCountThreshold();
        if (getCounter().incrementAndGet() >= countThreshold) {
            getCounter().set(0);
            log.debug("船速触发数量阈值:{} ", countThreshold);
            preSpeed = speed;
            return;
        }
        data.setSpeed(preSpeed);
    }

}
